package cn.edu.cug.cs.gtl.plugins.h3dfile;

import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.actions.AbstractAction;
import cn.edu.cug.cs.gtl.apis.ui.modeller.ModellerApp;


import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;

public class SaveH3DFileAction extends AbstractAction {

    @Override
    public void initialize(AbstractApplication theApp) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("h3dfile_resource", Locale.getDefault());

        name=resourceBundle.getString("menu.file.save_as_h3d_file");
        menuItem.setText(name);
        //button.setText(name);
        //button.setToolTipText(name);


        this.theApp = theApp;
        menuItem.addActionListener(this);
        //button.addActionListener(this);
        theApp.getMainFrame().getFileMenu().add(menuItem);
        //theApp.getMainFrame().getFileToolBar().add(button);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        final FileFilter h3dFileFilter = new H3DFileFilter();

        final JFileChooser h3dFileChooser = new JFileChooser(
                new File(System.getProperty("user.dir")));
        h3dFileChooser.setFileFilter(h3dFileFilter);
        h3dFileChooser.removeChoosableFileFilter(h3dFileChooser.getAcceptAllFileFilter());

        if ( h3dFileChooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION )
            return;
        String fileName = h3dFileChooser.getSelectedFile().getAbsolutePath();
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            getModellerApp().getModel3dUIApp().getProject().writeTo(fileOutputStream);
            fileOutputStream.close();
        }
        catch (IOException exception){
            exception.printStackTrace();
        }
    }

    public ModellerApp getModellerApp(){
        return (ModellerApp) theApp;
    }

}
